#include"tcp_server.h"
#include<string.h>
#include "config_file.h"
#include"echoMessage.pb.h"

// 设置路由分发机制
// typedef void msg_callback(const char *data, uint32_t len, int msgid, net_connection* net_conn, void *args);
void call_back1(const char *data, uint32_t len, int msgid, net_connection* net_conn, void *args){
    
    protobuf_test::EchoMessage request, response;

    // 解包，将data中的proto协议解析出来放入request中
    request.ParseFromArray(data, len);
    // printf("content = %s", request.content());
    // printf("ID = %d\n", request.id());
    
    // 回显，制作一个新的proto数据包
    response.set_id(request.id());
    response.set_content(request.content());
    
    // 将response序列化
    std::string responseString;
    response.SerializeToString(&responseString);

    // 将回执的message发送给客户端
    net_conn->send_message(responseString.c_str(), responseString.size(), msgid);


}



int main(){
    event_loop loop;

    // 加载配置文件
    config_file::setPath("./reactor.conf");
    std::string ip = config_file::instance()->GetString("reactor", "ip", "0.0.0.0");
    short port = config_file::instance()->GetNumber("reactor", "port", 8888);
    printf("ip: %s\tport: %d\n", ip.c_str(), port);

    // 允许连接的最大数
    int maxConn = config_file::instance()->GetNumber("reactor", "maxConn", 100);
    // 线程池个数，建议配置个数和CPU个数一致
    int thread_cnt = config_file::instance()->GetNumber("reactor", "threadNum", 3);  
    printf("maxConn: %d\tthread_cnt: %d\n", maxConn, thread_cnt);
   
   
    //创建套接字
    tcp_server server(&loop, ip.c_str(), port, maxConn, thread_cnt);

    // 注册msgid的回调函数 
    server.add_msg_router(1, call_back1);

    // 进入循环开始监听
    loop.event_process();

    return 0;
}
